﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LogHelper
{
    public class Log
    {
        private static Log mLog = null;

        public static Log Logger
        {
            get
            {
                if (mLog == null)
                {
                    mLog = new Log();
                }
                return mLog;
            }
        }

        private string mLogPath = "";

        public string LogPath
        {
            get
            {
                return mLogPath;
            }
            set
            {
                mLogPath = value;
            }
        }

        private FileStream mFileStream = null;

        private Log()
        {
        }

        public void Open()
        {
            mFileStream = new FileStream(LogPath, FileMode.OpenOrCreate);
        }

        public void Write(string msg)
        {
            StringBuilder sbd = new StringBuilder();
            sbd.AppendLine("[" + DateTime.Now.ToString() + "]----------------------------------------");
            sbd.AppendLine(msg);
            sbd.AppendLine("------------------------------------------------------------------------------------");
            byte[] bytmsg = UnicodeEncoding.UTF8.GetBytes(sbd.ToString());
            mFileStream.Write(bytmsg, 0, bytmsg.Length);
            mFileStream.Flush();
        }

        public string ReadLog()
        {
            try
            {
                List<byte> msg = new List<byte>();
                byte[] log = new byte[1024];
                while (mFileStream.Read(log, 0, log.Length) > 0)
                {
                    msg.AddRange(log);
                }
                return UnicodeEncoding.UTF8.GetString(msg.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
